//
//  MapViewController.m
//  Meroad
//
//  Created by 郭孝通 on 2019/1/25.
//  Copyright © 2019 郭孝通. All rights reserved.
//

#import "MapViewController.h"
#import "CustomAnnotationView.h"
#import "AMapSearchKit/AMapSearchKit.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "AppDelegate.h"

@interface MapViewController ()<MAMapViewDelegate, AMapSearchDelegate, CustomAnnotationDelegate>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, copy) NSMutableArray *pointAnnotationArray;
@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) AMapRoute *route;

@property (nonatomic) NSInteger currentCourse;
@property (nonatomic) NSInteger totalCourse;

@property (nonatomic, strong) UIBarButtonItem *previousItem;
@property (nonatomic, strong) UIBarButtonItem *nextItem;

@property (nonatomic) CLLocationCoordinate2D startCoordinate;
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;

@property (nonatomic, strong) MAPolyline *polyline;

@property (weak, nonatomic) IBOutlet UIButton *userButton;
- (IBAction)refreshAction:(UIButton *)sender;
- (IBAction)userButtonAction:(UIButton *)sender;
- (void)initMap:(MAMapView *)mapView;

@end

@implementation MapViewController

#pragma mark 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [AMapServices sharedServices].enableHTTPS = YES;
    
    [AMapServices sharedServices].apiKey = @"5ba2e81d035c1e30c936986b32c91361";
    
    _mapView = [[MAMapView alloc] init];
    
    _pointAnnotationArray = [NSMutableArray array];
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;

    _mapView.frame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.size.width, self.view.bounds.size.height + 40);
    
    //把地图添加至view
    [self.view addSubview:_mapView];
    [self.view sendSubviewToBack:_mapView];

    [self refreshAllPoint];
    
    [self initMap:_mapView];
}

- (void)viewWillDisappear:(BOOL)animated{
    AppDelegate *_rootDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [_rootDelegate.draverView hide];
    if([[[_rootDelegate.window subviews] lastObject] isKindOfClass:[CustomCalloutView class]]){
        CustomCalloutView *calloutView = [[_rootDelegate.window subviews] lastObject];
        [calloutView hide];
    }
}

#pragma mark initial

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)initMap:(MAMapView *)mapView{
    
    //进入地图就显示定位小蓝点
    mapView.showsUserLocation = YES;
    mapView.userTrackingMode = MAUserTrackingModeFollow;

    MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
    r.showsAccuracyRing = NO; //精度圈

    r.showsHeadingIndicator = YES; //蓝点方向指向
    //r.fillColor    精度圈填充颜色
    //r.strokerColor    精度圈边线颜色
    r.lineWidth = 2;  //精度圈边线宽度
    r.enablePulseAnnimation = YES;  //精度圈内部蓝点律动效果
    //r.locationDotBgColor   定位蓝点背景颜色
    //r.locationDotFillColor  定位蓝点颜色
    //r.image  定位蓝点的图标

    [mapView updateUserLocationRepresentation:r];
    
    //缩放手势
    mapView.zoomEnabled = YES;
    
    //设置地图的缩放级别
    [mapView setZoomLevel:17 animated:YES];
    
    //滑动手势
    mapView.scrollEnabled = YES;
    
    //地图平移时，缩放级别不变，可通过改变地图的中心点来移动地图
    //[_mapView setCenterCoordinate:center animated:YES];
    
    //旋转手势
    mapView.rotateEnabled = YES;
    
    //设置地图的旋转角度
    [mapView setRotationDegree:60.f animated:YES duration:0.5];
    
    //倾斜手势
    mapView.rotateCameraEnabled = YES;
    
    //设置倾斜角度
    [mapView setCameraDegree:30.f animated:YES duration:0.5];
    
    //藏地图指南针
    mapView.showsCompass = NO;
    
    //指定屏幕中心点的手势操作
    MAMapStatus *status = [mapView getMapStatus];
    status.screenAnchor = CGPointMake(0.5, 0.76);       //地图左上角为(0,0)点，右下角为(1,1)点
    [mapView setMapStatus:status animated:NO];
    
    mapView.delegate = self;
    
}

/*
- (void)locationMark:(MAMapView *)mapView{
    if(![_pointAnnotationArray count]){
        for(ToiletModel *toilet in self.toiletModels){
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = toilet.location.coordinate;
            pointAnnotation.title = [NSString stringWithFormat:@"厕所编号: %@",toilet.uuid];
            pointAnnotation.subtitle = [NSString stringWithFormat:@"%@",toilet.address];
            [_pointAnnotationArray addObject:pointAnnotation];
            NSLog(@"No pointAnnotation");
        }
    }
 
    else{
        for(int i = 0; i < [_pointAnnotationArray count]; i++){
            [mapView removeAnnotation:[_pointAnnotationArray objectAtIndex:i]];
        }
        
        [_pointAnnotationArray removeAllObjects];
        
        for(ToiletModel *toilet in self.toiletModels){
            MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
            pointAnnotation.coordinate = toilet.location.coordinate;
            pointAnnotation.title = [NSString stringWithFormat:@"厕所编号: %@",toilet.uuid];
            pointAnnotation.subtitle = [NSString stringWithFormat:@"%@",toilet.address];
            [_pointAnnotationArray addObject:pointAnnotation];
        }
    }
 
}
*/

#pragma mark delegate

- (void)searchRoutePlanningWalk{
    self.startAnnotation.coordinate = self.startCoordinate;
    self.destinationAnnotation.coordinate = self.destinationCoordinate;
    
    AMapWalkingRouteSearchRequest *navi = [[AMapWalkingRouteSearchRequest alloc] init];
    
    //出发点
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    
    //目的地
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapWalkingRouteSearch:navi];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    NSLog(@"开始定位");
    if([annotation isKindOfClass:[MAUserLocation class]]){
        return nil;
    }
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *reuseIndentifier = @"annotationReuseIndentifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndentifier];
        
        if(annotationView == nil){
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndentifier];
        }
        
        annotationView.delegate = self;
        
        for(ToiletModel *toilet in self.toiletModels){
            if(annotation.coordinate.latitude == toilet.latitude && annotation.coordinate.longitude == toilet.longitude ){
                CGFloat rate = (CGFloat)toilet.spareHolesNumber / (CGFloat)toilet.allHolesNumber;
                annotationView.model = toilet;
                if(rate <= 0.3){
                    annotationView.image = [UIImage imageNamed:@"水滴红"];
                }else if(rate <= 0.6){
                    annotationView.image = [UIImage imageNamed:@"水滴黄"];
                }else{
                    annotationView.image = [UIImage imageNamed:@"水滴蓝"];
                }
            }
        }
        annotationView.canShowCallout = NO;
        annotationView.centerOffset = (CGPointMake(0, -18));
        return annotationView;
    }

    return nil;
    
}

- (void)mapInitComplete:(MAMapView *)mapView{
    NSLog(@"init complete");
    CGPoint userPoint = [_mapView convertCoordinate:self.mapView.userLocation.coordinate toPointToView:_mapView];
    CGPoint userChangedPoint = CGPointMake(userPoint.x, userPoint.y + SCREEN_HEIGHT / 2.7);
    CLLocationCoordinate2D coordinate = [_mapView convertPoint:userChangedPoint toCoordinateFromView:_mapView];
    [_mapView setCenterCoordinate:coordinate];

}


//- (void)mapViewDidFinishLoadingMap:(MAMapView *)mapView{
//    NSLog(@"did finish loading map");
//    CGPoint userPoint = [_mapView convertCoordinate:self.mapView.userLocation.coordinate toPointToView:_mapView];
//    CGPoint userChangedPoint = CGPointMake(userPoint.x, userPoint.y + SCREEN_HEIGHT / 2.7);
//    CLLocationCoordinate2D coordinate = [_mapView convertPoint:userChangedPoint toCoordinateFromView:_mapView];
//    [_mapView setCenterCoordinate:coordinate];
//}

- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if(response.route == nil){
        return;
    }
    
    //解析response获取路径信息
    if(response.count > 0){
        AMapPath *path = response.route.paths[0];
        [_mapView removeOverlay:_polyline];
        _polyline = [self polylinesForPath:path];
        [_mapView addOverlay:_polyline];
    }
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"Error: %@", error);
}

- (void)DidSelectedAnnotation:(MAPointAnnotation *)annotation{
    self.startCoordinate = self.mapView.userLocation.coordinate;
    self.destinationCoordinate = annotation.coordinate;
    [self searchRoutePlanningWalk];
}

- (void)removePolyline{
    [self.mapView removeOverlay:_polyline];
}


#pragma mark action

- (IBAction)userButtonAction:(UIButton *)sender {
    AppDelegate *_rootDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if([[[_rootDelegate.window subviews] lastObject] isKindOfClass:[CustomCalloutView class]]){
        CustomCalloutView *calloutView = [[_rootDelegate.window subviews] lastObject];
        [calloutView hide];
        [self.mapView removeOverlay:_polyline];
    }
    [_rootDelegate.draverView show];
}

- (IBAction)refreshAction:(UIButton *)sender {
    CGPoint userPoint = [_mapView convertCoordinate:self.mapView.userLocation.coordinate toPointToView:_mapView];
    CGPoint userChangedPoint = CGPointMake(userPoint.x, userPoint.y + SCREEN_HEIGHT / 2.7);
    CLLocationCoordinate2D coordinate = [_mapView convertPoint:userChangedPoint toCoordinateFromView:_mapView];
    [_mapView setCenterCoordinate:coordinate];
}

#pragma mark 重写get方法(懒加载)

- (UserModel *)userModel{
    if (_userModel == nil) {
        AppDelegate *_rootDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        _userModel = _rootDelegate.userModel;
    }
    return _userModel;
}

- (NSArray *)toiletModels{
    if (_toiletModels == nil) {
        AppDelegate *_rootDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        _toiletModels = _rootDelegate.toiletModels;
    }
    return _toiletModels;
}

#pragma mark 路线解析
- (MAPolyline *)polylinesForPath:(AMapPath *)path{
    if(path == nil || path.steps.count == 0){
        return nil;
    }
    NSMutableString *polylineMutableString = [@"" mutableCopy];
    for(AMapStep *step in path.steps){
        [polylineMutableString appendFormat:@"%@;",step.polyline];
    }
    
    NSUInteger count = 0;
    CLLocationCoordinate2D *coordinates = [self coordinatesForString:polylineMutableString
                                                     coordinateCount:&count
                                                          parseToken:@";"];
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates
                                                          count:count];
    free(coordinates);
    coordinates = NULL;
    return polyline;
}

#pragma mark 经纬度解析
- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string coordinateCount:(NSUInteger *)coordinateCount parseToken:(NSString *)token{
    if(string == nil){
        return NULL;
    }
    
    if(token == nil){
        token = @",";
    }
    
    NSString *str = @"";
    if(![token isEqualToString:@","]){
        str = [string stringByReplacingOccurrencesOfString:token
                                                withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if(coordinateCount != NULL){
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(count * sizeof(CLLocationCoordinate2D));
    
    for(int i = 0; i < count; i++){
        coordinates[i].longitude = [[components objectAtIndex:2 * i] doubleValue];
        coordinates[i].latitude = [[components objectAtIndex:2 * i + 1] doubleValue];
    }
    
    return coordinates;
}

#pragma mark 绘制折线
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    if([overlay isKindOfClass:[MAPolyline class]]){
        MAPolyline *polyline = (MAPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:polyline];
        
        //添加纹理图片
        //若设置了纹理图片，设置线颜色、连接类型和端点类型将无效
        polylineRenderer.strokeImage = [UIImage imageNamed:@"wenli"];
        polylineRenderer.lineWidth = 20.f;
        
//        polylineRenderer.strokeColor = [UIColor colorWithRed:0 green:1 blue:0.5 alpha:0.8];
//        polylineRenderer.lineJoinType = kMALineCapRound;
//        polylineRenderer.lineCapType = kMALineCapRound;
//        polylineRenderer.miterLimit = 1.f;
        
        return polylineRenderer;
    }
    return nil;
}

#pragma mark others

-(void)refreshAllPoint{
    //[_mapView forceRefresh];
    //[_mapView removeAnnotations:_pointAnnotationArray];
    //[self locationMark:_mapView];
    //NSLog(@"Refresh!!!");
    
    if([_pointAnnotationArray count]){
        [_mapView removeAnnotations:_pointAnnotationArray];
        [_pointAnnotationArray removeAllObjects];
    }
    
    for(ToiletModel *toilet in self.toiletModels){
        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
        pointAnnotation.coordinate = toilet.location.coordinate;
        [_pointAnnotationArray addObject:pointAnnotation];
    }
    [_mapView addAnnotations:_pointAnnotationArray];
    
}

//刷新某一个点
-(void)refreshOnePoint:(NSInteger)num{
    ToiletModel *toilet = [self.toiletModels objectAtIndex:num];
    
    //该点已存在时刷新point
    for(MAPointAnnotation *pointAnnotation in _pointAnnotationArray){
        if(pointAnnotation.coordinate.latitude == toilet.latitude && pointAnnotation.coordinate.longitude == toilet.longitude ){
            [_mapView removeAnnotation:pointAnnotation];
            [_mapView addAnnotation:pointAnnotation];
            return;
        }
    }
    
}

//刷新某一个点
-(void)addOnePoint:(NSInteger)num{
    ToiletModel *toilet = [self.toiletModels objectAtIndex:num];
    
    //该点不存在时加point
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    pointAnnotation.coordinate = toilet.location.coordinate;
    [_pointAnnotationArray insertObject:pointAnnotation atIndex:num];
    [_mapView addAnnotation:pointAnnotation];
    
}

@end
